<?php

namespace App\Repositories\Api;

use App\Models\SpreadPlatform;
use App\Repositories\PictureMappingRepository;

class SpreadPlatformRepository
{
    public function saveOrUpdate($params = [])
    {
        $data['uid'] = intval($params['uid']);
        $data['type'] = intval($params['account_type']);
        $data['note'] = trim($params['note']) ?? "";
        $data['link'] = trim($params['link']) ?? "";
        $data['account_id'] = trim($params['account_id']) ?? "";
        $data['account_name'] = trim($params['account_name']) ?? "";
        $data['create_time'] = $data['update_time'] = date("Y-m-d H:i:s");

        return SpreadPlatform::insertGetId($data);
    }

    public function getPages($filter = [], $pageSize = 10, $pageNum = 1)
    {
        $res = SpreadPlatform::query()
            ->where("uid", $filter['uid'])
            ->orderBy('id', 'desc')
            ->paginate($pageSize, "*", null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            if ($v['type'] > 0) {
                $v['type_name'] = spread_platform_type($v['type']);
            }
        }

        return $res;
    }

    public function getOne($id = null)
    {
        $res = SpreadPlatform::query()->where(['id' => $id])->first();
        if (empty($res)) {
            return null;
        }

        $res['pictures'] = (new PictureMappingRepository())->getMappingBySearch([
            'object_id' => $id,
            'object_type' => "spread_platform"
        ]);

        $res['status_title'] = check_status($res['status']);

        $res['type'] > 0 && $res['type_name'] = spread_platform_type($res['type']);
        return $res;
    }

}